package com.thzy.bbs.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.thzy.bbs.R;
import com.thzy.bbs.common.ActivityConfig;
import com.thzy.bbs.common.AddressConfig;
import com.thzy.bbs.common.CommonUtils;
import com.thzy.bbs.common.Constants;
import com.thzy.bbs.entity.MessageNumber;
import com.thzy.bbs.google.FCMSend;
import com.thzy.bbs.setting.SetFunction;
import com.thzy.bbs.setting.SetMainSkip;
import com.thzy.bbs.setting.SetWebChromeClient;
import com.thzy.bbs.setting.SetWebClient;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * webView主界面
 *
 * @author Lirui
 */
@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
    /**
     * 是否上传图片返回的webView
     */
    public static boolean isUploading = false;
    /**
     * 是否打开activity
     */
    public static boolean isStart = false;

    /**
     * 美拍跳转标识
     */
    public static String isMeiPaiBack = "2";

    @ViewInject(R.id.web_view)
    private WebView webView;

    public WebView getWebView() {
        return webView;
    }

    /**
     * 当程序在后台跳转到这里获取是否有关注
     */
    private Boolean attention;
    /**
     * 当程序在后台跳转到这里获取跳转地址
     */
    private String url;

    /**
     * 退出控制标识
     */
    private boolean isExit = false;
    /**
     * 主线程接受子线程消息
     */
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == Constants.Code.TWO_OUT_SYSTEM) {
                super.handleMessage(msg);
                isExit = false;
            }
        }
    };

    @Override
    protected void onStop() {
        isStart = false;
        super.onStop();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x.view().inject(this);
        CommonUtils.webView = this.webView;
        getMessage();
        setWebView();
    }


    @Override
    protected void onStart() {
        super.onStart();
        isStart = true;
        if (isUploading) {
            isUploading = false;
            return;
        }
        if (isMeiPaiBack.equals(ActivityConfig.parameterName.MEIPAI_GO_BACK_HISTORY)) {
            //处理返回到美拍
            WebBackForwardList webBackForwardList = CommonUtils.webView.copyBackForwardList();
            try {
                url = webBackForwardList.getItemAtIndex(webBackForwardList.getSize() - 2).getUrl();
            } catch (Exception e) {
                url = AddressConfig.ConfigAddress.INDEX_URL;
            }
            isMeiPaiBack = ActivityConfig.parameterName.MEIPAI_NOT_GO_BACK_HISTORY;
            webView.loadUrl(url);
            return;
        }
        if (isMeiPaiBack.equals(ActivityConfig.parameterName.MEIPAI_NOT_GO_BACK_HISTORY)) {
            webView.loadUrl(CommonUtils.functionJoin(Constants.JsFunctionName.PHOTO_TO_MAIN, String.valueOf(isUploading)));
        }
    }

    /**
     * 程序后台跳转过来发送消息
     */
    private void getMessage() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String attention = bundle.getString(ActivityConfig.fcmParameterName.HAVE_ATTENTION);
            String url = bundle.getString(ActivityConfig.fcmParameterName.URL);
            this.attention = attention != null && Boolean.parseBoolean(attention);
            this.url = url == null ? null : AddressConfig.ConfigAddress.URL_HAND + url;
        }
    }

    /**
     * 设置vebView
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setAllowFileAccessFromFileURLs(true); // 设置是否允许通过file
        // url加载的Javascript读取其他的本地文件
        webSettings.setAllowUniversalAccessFromFileURLs(true);// 设置是否允许通过file
        // url加载的Javascript可以访问其他的源
        webSettings.setDomStorageEnabled(true);// H5本地数据存储需要开启
        webSettings.setJavaScriptEnabled(true);// 允许使用js
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);// 支持通过js打开新的窗口

        webSettings.setUseWideViewPort(true);// 设置此属性，可任意比例缩放
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 设置缓存模式（LOAD_DEFAULT：根据cache-control决定是否从网络上取数据），无网络的情况已经处理，不需根据有无网络去设置缓存模式
        webSettings.setAppCacheEnabled(true);// 开启缓存
        webSettings.setLoadsImagesAutomatically(true);// 设置当前webview是否需要加载图片
        webView.addJavascriptInterface(new SetFunction(this, new SetMainSkip(
                this)), ActivityConfig.parameterName.JS_FUNCTION_NAME);//设置js与java互调方法
        // 设置UserAgent
        String ua = webView.getSettings().getUserAgentString();
        webView.getSettings().setUserAgentString(Constants.EquipmentInfo.USER_AGENT + ua);
        webView.setWebChromeClient(new SetWebChromeClient());// 设置弹框信息处理
        webView.setWebViewClient(new SetWebClient(this));
        webViewSkip();
    }

    /**
     * webView 跳转
     */
    private void webViewSkip() {
        if (url == null) {
            url = AddressConfig.ConfigAddress.INDEX_URL;
        }
        webView.loadUrl(url);
        //后台直接进入webView页面，修改数据库数据
        if (null != attention) {
            FCMSend fcMsend = new FCMSend();
            fcMsend.updateDb(new MessageNumber(attention, !attention));
        }
    }

    /**
     * 按钮点击两次退出设置
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode != KeyEvent.KEYCODE_BACK || webView == null) {
            return super.onKeyDown(keyCode, event);
        }
        exit();
        //让前端跳转处理
        webView.loadUrl(CommonUtils.functionJoin(Constants.JsFunctionName.GO_BACK));
        return false;
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(Constants.Code.TWO_OUT_SYSTEM, 1000);
        } else {
            finish();
        }
    }
}
